import uart
import os
from uasyncio.synchro import Lock
Lock = Lock()

class state:pass
state = state()

async def ainput(prompt=None, password=False, nl=False,pre_render=None,post_render=None):
    global Lock, render

    input = __import__('uio').StringIO()
    input.seek(0)
    tell = 0
    current = prompt

    await Lock.acquire()
    try:
        uart.echo(current)
        while use.lives:
            if uart.UART.any():
                current = uart.UART.read(1)
                chr = ord(current)
                # 10176
                with uses('readline'):
                    pass

                if 31<chr<127:
                    input.seek(tell)
                    input.write(current)
                    tell += 1
                elif chr==127:
                    tell -= 1 if tell>0 else 0
                elif chr in [13,10]: #???? flush 10 ?
                    if nl:
                        uart.echo(b'\n')
                    current = None
                    break
                uart.echo(current)
                current = None
            elif uart.render:
                #render sg and custom here
                uart.end()
                uart.render(pre_render, post_render)
                uart.begin()

            await aio.asleep_ms(1)

        input.seek(0)
        return input.read(tell)
    finally:
        Lock.release()
        uart.end() #os.dupterm( UART , 1)
